#include <qdebug.h>
#include <qprocess.h>
#include <qmessagebox.h>
#include <qfiledialog.h>
#include <qmessagebox.h>

#include "HexJudger.h"
#include "SetupDialog.h"
#include "SimulateThread.h"

#include "hexboard.h"

HexJudger::HexJudger(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);

	//connect(engine, &QProcess::readyReadStandardOutput, this, &HexJudger::onEngineDataReady);
	connect(ui.actionSetup, &QAction::triggered, this, &HexJudger::onSetupClicked);
	connect(ui.actionStart, &QAction::triggered, this, &HexJudger::onStartClicked);
}

void HexJudger::killProcess(QProcess * process)
{
	if (process != nullptr)
	{
		process->kill();
		delete process;
		process = nullptr;
	}
}

void HexJudger::writeProcess(QProcess * process, const QString & str)
{
	process->write(str.toLatin1().constData(), str.length());
	process->waitForBytesWritten();
}

void HexJudger::onSetupClicked()
{
	SetupDialog * dlg = new SetupDialog(this);
	connect(dlg, &SetupDialog::sendData, this, &HexJudger::receiveData);
	dlg->show();
}

void HexJudger::onStartClicked()
{
	if (engine1Filename == "" || engine2Filename == "" || times <= 0 || times > 20 || mode == 0 || (mode == 2 && first == 0))
	{
		QMessageBox::critical(this, "error", "please complete setup first!");
		return;
	}

	SimulateThread * thread = new SimulateThread(this);
	connect(thread, &SimulateThread::makeMove, this, &HexJudger::receiveMove);
	connect(thread, &SimulateThread::endOfOneGame, this, &HexJudger::clearBoard);
	thread->setParam(engine1Filename, engine2Filename, times, mode, first);
	thread->start();
}

void HexJudger::receiveData(QString & engine1, QString & engine2, int times, int mode, int first)
{
	engine1Filename = engine1;
	engine2Filename = engine2;
	this->times = times;
	this->mode = mode;
	this->first = first;
	//qDebug() << "aaa";
}

void HexJudger::receiveMove(int pos, int player)
{
	if (player == 1)
	{
		ui.board->setGridColor(pos, Qt::red);
	}
	else if (player == 2)
	{
		ui.board->setGridColor(pos, Qt::blue);
	}
	ui.board->update();
}

void HexJudger::clearBoard()
{
	ui.board->clearColor();
	ui.board->update();
}